package com.quansu.trailertiger.base

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.caogen.cg_wl_kt.base.BaseViewModel

/**
 * Mine Base Activity
 *
 * @param <VM>
 * @param <B>
</B></VM> */
open class BActivity< VB : ViewBinding,VM : BaseViewModel> constructor(
    val inflater: (LayoutInflater) -> VB,
    private val clazz: Class<VM>
): AppCompatActivity() , View.OnClickListener{

    var flag = false
    public lateinit var binding: VB
    public lateinit var viewModel: VM
    public lateinit var activityResultLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=inflater(layoutInflater)
        setContentView(binding.root)
        viewModel=ViewModelProvider(this).get(clazz)

        setActivityResult()
        initView()
        setListener()
    }

    open fun setActivityResult(){

    }

    open fun initView(){

    }
    open fun setListener(){

    }

    override fun onClick(v: View?) {

    }

    protected open fun setOnClickListener(vararg views: View?) {
        for (v in views) {
            if (null == v) throw NullPointerException("不能传入空的控件!")
            v.setOnClickListener(this)
        }
    }

    override fun onResume() {
        super.onResume()
        //注：回调 1
        flag = true

    }

    override fun onPause() {
        super.onPause()
        //注：回调 2
        flag = false
    }

    override fun onStop() {
        super.onStop()
        if (!isAppOnForeground()) {
            //app 进入后台
            Log.e("-shy-", "onStop: 程序进入后台")
            flag = true
        }
    }


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        //注：回调 3
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }


    /**
     * 程序是否在前台运行
     *
     * @return
     */
    open fun isAppOnForeground(): Boolean {

        val activityManager = applicationContext.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val packageName = applicationContext.packageName

        val appProcesses = activityManager
                .runningAppProcesses ?: return false
        for (appProcess in appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance === ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true
            }
        }

        return false
    }


}
